import type { FormInstance } from 'element-plus'
import type {
  UseTaskGroupHardwareEnumType,
  performActionEnumType
} from '~/store/monitorManagement/loopMonitorBox/typings'
import type { AllDayTasksFormValuesType } from './typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import dayjs from 'dayjs'
import {
  ElDialog,
  ElRow,
  ElCol,
  ElForm,
  ElFormItem,
  ElInput,
  ElRadioGroup,
  ElRadio,
  ElDatePicker,
  ElSelect,
  ElOption,
  ElButton,
  ElMessage,
  ElMessageBox
} from 'element-plus'
import InputTextarea from '~/components/ProForm/InputTextarea'
import useVuexGetters from '~/hooks/useVuexGetters'
import { SPAN_STYLE_DOUBLE, MODAL_NORMAL_WIDTH } from '~/utils/const'
import styles from '../../index.module.scss'

export default defineComponent({
  name: 'AllDayTasksModal',
  props: ['detail', 'doClose'],
  setup(props: { detail: AllDayTasksFormValuesType; doClose: () => void }) {
    const store = useStore()
    const ruleFormRef = ref<FormInstance>()
    const formValues = reactive<AllDayTasksFormValuesType>({})
    const submitLoadingRef = ref<boolean>()
    const loopSwitchGroupState = useVuexGetters('loopSwitchGroup', [
      'useTaskGroupHardwareSelectList',
      'noUseTaskGroupHardwareSelectList'
    ])
    const switchLightStrategyState = useVuexGetters('switchLightStrategy', [
      'performActionSelectList'
    ])

    const handleSubmitForm = () => {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validate(async (valid) => {
        if (!valid) return
        submitLoadingRef.value = true
        const params = {
          taskType: 3,
          ...formValues
        }
        if (formValues.taskTime?.length) {
          params.taskBegin = dayjs(formValues.taskTime[0]).format('YYYY-MM-DD')
          params.taskEnd = dayjs(formValues.taskTime[1]).format('YYYY-MM-DD')
        }
        if (formValues.taskGroupIdsList) params.taskGroupIds = formValues.taskGroupIdsList.join(',')
        params.taskTrem = params.taskTrem ? 1 : 0
        const res = await store.dispatch(
          formValues?.id
            ? 'switchLightStrategy/UpdateMonitoSwitchLightTaskInfo'
            : 'switchLightStrategy/AddMonitoSwitchLightTaskInfo',
          params
        )
        submitLoadingRef.value = false
        if (res?.success) {
          if (res?.data?.isSuccess === 0) {
            ElMessageBox.alert('确认提示', res?.data?.msg, {
              confirmButtonText: '确认',
              closeOnClickModal: false, // 点遮罩层不关弹窗
              draggable: true // 可拖拽
            })
              .then(() => {})
              .catch(() => {})
            return
          }
          ElMessage({ type: 'success', message: '操作成功' })
          props.doClose()
        }
      })
    }

    onMounted(() => {
      store.dispatch('loopSwitchGroup/GetUseTaskGroupHardwareList')

      if (!props.detail.id) return
      // 设置表单初始值
      Object.assign(formValues, props.detail, {
        taskGroupIdsList: props.detail?.taskGroupIds
          ? props.detail?.taskGroupIds?.split?.(',')
          : [],
        taskTime:
          props.detail?.taskBegin && props.detail?.taskEnd
            ? [props.detail?.taskBegin, props.detail?.taskEnd]
            : undefined
      })
    })

    return () => (
      <ElDialog
        width={MODAL_NORMAL_WIDTH}
        title={`${props?.detail?.id ? '编辑' : '新增'}全天任务`}
        modelValue={true}
        closeOnClickModal={false} // 点遮罩层不关弹窗
        draggable // 可拖拽
        beforeClose={props?.doClose}
        v-slots={{
          footer: () => (
            <>
              <ElButton type="primary" onClick={handleSubmitForm} loading={submitLoadingRef.value}>
                {props?.detail?.id ? '修改' : '保存'}
              </ElButton>
              <ElButton onClick={props.doClose}>取消</ElButton>
            </>
          )
        }}
      >
        <ElForm ref={ruleFormRef} model={formValues} labelWidth={90}>
          <ElRow>
            <ElCol>
              <ElFormItem
                prop="taskName"
                label="任务名称"
                rules={[
                  {
                    required: true,
                    min: 3,
                    max: 20,
                    message: '任务名称 3 ~ 20 字符'
                  }
                ]}
              >
                <ElInput
                  v-model={formValues.taskName}
                  placeholder="请输入任务名称"
                  {...{ minlength: 3, maxlength: 20 }}
                />
              </ElFormItem>
            </ElCol>
            <ElCol>
              <ElFormItem
                prop="taskTrem"
                label="有效周期"
                rules={[
                  {
                    required: true,
                    message: '请选择有效周期'
                  }
                ]}
              >
                <ElRadioGroup
                  style={{ width: '100%' }}
                  v-model={formValues.taskTrem}
                  onChange={() => ruleFormRef.value?.validateField(['taskTime'])}
                >
                  <ElRadio class={styles['all-day-task-radio']} label={0}>
                    长期有效
                  </ElRadio>
                  <ElRadio class={styles['all-day-task-radio']} label={1}>
                    <ElFormItem
                      prop="taskTime"
                      rules={[
                        {
                          required: formValues.taskTrem === 1,
                          message: '请选择时间范围'
                        }
                      ]}
                    >
                      <ElDatePicker
                        style={{ width: '100%' }}
                        type="daterange"
                        v-model={formValues.taskTime}
                        disabled={!formValues.taskTrem}
                        disabledDate={(time: Date) => time.getTime() < Date.now()}
                      />
                    </ElFormItem>
                  </ElRadio>
                </ElRadioGroup>
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_DOUBLE}>
              <ElFormItem prop="isDayOper" label="执行动作">
                <ElRadioGroup v-model={formValues.isDayOper}>
                  {switchLightStrategyState.performActionSelectList.value?.map(
                    (item: performActionEnumType) => (
                      <ElRadio key={item?.dictKey} label={item?.dictKey}>
                        {item?.dictValue}
                      </ElRadio>
                    )
                  )}
                </ElRadioGroup>
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_DOUBLE}>
              <ElFormItem
                prop="taskGroupIdsList"
                label="设备分组"
                rules={[
                  {
                    required: false,
                    message: '请选择设备分组'
                  }
                ]}
              >
                <ElSelect
                  v-model={formValues.taskGroupIdsList}
                  placeholder="请选择设备分组"
                  filterable
                  multiple
                  collapseTags
                >
                  {/* 新增时 */}
                  {!props?.detail?.id &&
                    loopSwitchGroupState.noUseTaskGroupHardwareSelectList.value?.map(
                      (item: UseTaskGroupHardwareEnumType) =>
                        item?.id && (
                          <ElOption
                            key={item?.id}
                            label={item?.groupName}
                            value={item?.id!}
                            disabled={
                              !!item?.isUsed && !props.detail?.taskGroupIds?.includes(item?.id)
                            }
                          />
                        )
                    )}
                  {/* 修改时 */}
                  {props?.detail?.id &&
                    loopSwitchGroupState.useTaskGroupHardwareSelectList.value?.map(
                      (item: UseTaskGroupHardwareEnumType) =>
                        item?.id && (
                          <ElOption
                            key={item?.id}
                            label={item?.groupName}
                            value={item?.id!}
                            disabled={
                              !!item?.isUsed && !props.detail?.taskGroupIds?.includes(item?.id)
                            }
                          />
                        )
                    )}
                </ElSelect>
              </ElFormItem>
            </ElCol>
          </ElRow>
          <ElFormItem prop="taskDesc" label="备注说明">
            <InputTextarea
              v-model:inputTextareaValue={formValues.taskDesc}
              placeholderName="请输入内容"
              limitLength={200}
            />
          </ElFormItem>
        </ElForm>
      </ElDialog>
    )
  }
})
